package Chuong06;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.plaf.BorderUIResource;

public class Bai05 extends JFrame implements Runnable, ActionListener{

	JPanel canvas = new JPanel();
	JPanel panel = new JPanel();
	
	Thread t;
	
	JButton btnRun = new JButton("Run"),
			btnStop = new JButton("Stop"),
			btnClose = new JButton("Close");
	
	public static void main(String[] args) {
		Bai05 frm = new Bai05();
		frm.setVisible(true);
		frm.setSize(500, 400);
	}
	
	public Bai05() {
		super("Bài 05 - Chương 06");
		add(canvas, BorderLayout.CENTER);
		panel.setBackground(Color.DARK_GRAY);
		panel.add(btnRun);
		panel.add(btnStop);
		panel.add(btnClose);
		add(panel, BorderLayout.SOUTH);
		
		btnRun.addActionListener(this);
		btnStop.addActionListener(this);
		btnClose.addActionListener(this);
		
		t = new Thread(Bai05.this);
	}
	
	public void run() {
		Graphics g = canvas.getGraphics();
		int x=60,y=60, dx=1, dy=1;
		
		while(true){
			
				//g.setColor(new Color((float)Math.random(),(float)Math.random(),(float)Math.random()));
				g.setColor(Color.RED);
				g.fillOval(x, y, 20, 20);
				
				try{ 
					Thread.sleep(10);
				}
				catch(Exception e){}
				
				g.setColor(canvas.getBackground());
				g.fillOval(x, y, 20, 20);
			
				x += dx; y += dy;
				
				if(x<0 || x>canvas.getWidth()-20) dx=-dx;
				if(y<0 || y>canvas.getHeight()-20) dy=-dy;
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == btnRun){
			t.start();
		}
		
		if(e.getSource() == btnStop){
			t.stop();
		}
		
		if(e.getSource() == btnClose){
			System.exit(1);
		}
		
	}

}
